<template>
  <div>
    <el-dialog title="新增" :visible.sync="dialogVisibleAddType" width="30%">
      <div>
        <el-form
          ref="addForm"
          :model="formAdd"
          :rules="rulesAdd"
          label-width="80px"
        >
          <el-form-item label="分类名称">
            <el-input
              v-model="formAdd.name"
              placeholder="请输入分类名称"
            ></el-input>
          </el-form-item>
          <el-form-item label="上级id">
            <el-cascader
              v-model="formAdd.parent_id"
              :options="fatherOptions"
              :props="{
                label: 'name',
                value: 'id',
                checkStrictly: true,
                children: 'children',
                expandTrigger: 'click',
              }"
              @change="handleChangeTop"
            ></el-cascader>
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancelDialogAdd">取 消</el-button>
        <el-button type="primary" @click="sureDialogAdd('addForm')"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  props: ["tableDataRecharge"],
  data() {
    return {
      dialogVisibleAddType: false,
      formAdd: {
        name: "",
        parent_id: "",
      },
      rulesAdd: {
        name: [{ required: true, message: "请输入分类名称", trigger: "blur" }],
      },
      fatherOptions: [],
    };
  },
  watch: {
    tableDataRecharge: {
      handler(newVal) {
        this.fatherOptions = newVal;
      },
    },
  },
  methods: {
    // 确定
    sureDialogAdd(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.$emit("sureDialogAdd", this.formAdd);
        } else {
          return false;
        }
      });
    },

    // 取消
    cancelDialogAdd() {
      this.$emit("cancelDialogAdd", "");
    },

    handleChange(value) {
      console.log(value, "级联选择器");
    },

    // 处理上级id
    handleChangeTop(val) {
      console.log(val, "上级id");
      this.$emit("handleChangeTop", val);
      this.formAdd.parent_id = val[val.length - 1];
    },
  },
};
</script>
<style scoped lang="scss"></style>
